<?php

namespace App\Http\Controllers\Admin;

use App\Models\ActivitySale;
use App\Models\ActivityType;
use App\Services\IssueService;
use App\Services\UploadService;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Http\Controllers\LayuiController as Layui;
use App\Exceptions\FormException;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\View;
use Illuminate\Support\Facades\Validator;
use Mockery\Exception;

class IssueController extends Controller
{
    /**
     * 列表页面
     *
     * @Author   stonefall
     * @DateTime 2019-06-5
     * @return   [type]     [description]
     */
    public function index()
    {
        return view('Admin.issue.index');
    }

    /**
     * 获取数据
     * @author stonefall
     * @return [json]           [数组格式]
     */
    public function table(Request $request)
    {
        $payload = $request->all();
        $activityData = ActivityType::orderBy('id', 'ASC')
            ->where(function ($query) use ($payload) {
                $query->Where('type', 2);
                if (isset($payload['status']) && $payload['status'] != '') {
                    $query->Where('status', $payload['status']);
                }
            })
            ->paginate($request->get('limit', 10));
        foreach ($activityData as $item => $value){
             $value->end_time =  strtotime($value->end_at) + 3600*24 > time();
        }

        return Layui::tableJson($activityData, 0, 1);
    }

    /**
     * 获取数据
     * @author stonefall
     * @return [json]           [数组格式]
     */
    public function activity_table(Request $request)
    {
        $payload = $request->all();
        $activityData = ActivitySale::orderBy('id', 'ASC')
            ->where(function ($query) use ($payload) {
                $query->Where('activity_type', ActivitySale::TYPE_TWO);
                $query->Where('issue_type', 2);
                if (isset($payload['id']) && $payload['id'] != '') {
                    $query->Where('activity_type_id', $payload['id']);
                }
            })
            ->get();
        return Layui::tableJson($activityData, 0, 1);
    }

    /**
     * 获取数据
     * @return [json]           [数组格式]
     */
    public function activity_interim_table()
    {
        $redis = app('redis.connection');
        $user = Auth::guard('admin')->user();
        $name = 'activity_' . $user->id;
        $aa = $redis->get($name);
        $array = json_decode($aa,true);
        return Layui::tableJson($array, 0, 1);
    }

    /**
     * 编辑AJAX保存操作
     * @name update
     * @param void
     * @author stonefall
     * @return JsonStr
     * @datetime 2019/5/21 10:11
     */
    public function activity_store(Request $request){
        $payload = $request->all(['rule_type', 'full', 'less', 'activity_time', 'activity_name']);

        $rule = [
            'rule_type' => 'required|in:1,2',//
            'full' => ['required_if:rule_type,2', function($attribute, $value, $fail) {
                if ($value){
                    if (!preg_match('/^[0-9]+$/',$value)  ) {
                        return $fail('满多少请输入数字');
                    }
                }
            }],
            'less' => ['required','numeric', function($attribute, $value, $fail) {
                if ($value){
                    if (!preg_match('/^[0-9]+$/',$value)  ) {
                        return $fail('减多少请输入数字');
                    }
                }
            }],
            'activity_time' => 'required|numeric',
            'activity_name' => 'required',
        ];
        $message = [
            'rule_type.required' => '请选择优惠类型',
            'rule_type.in' => '请输入正确的优惠类型',
            'full.required_if' => '请输入满多少',
            'less.required' => '请输入减多少',
            'activity_time.required' => '请输入有效期',
            'activity_name.required' => '请输入优惠券',
            'activity_time.numeric' => '有效期请输入数字',
        ];

        if ($payload['rule_type'] == ActivitySale::RULE_TYPE_TWO){
            if ((int)$payload['full'] < (int)$payload['less']){
                throw new FormException('满多少请输入大于等于减的数字');
            }
//            $activity_name = '满' . $payload['full'] . '减' . $payload['less'] . '元';
        }
//        else{
//            $activity_name = '立减' . $payload['less'] . '元';
//        }
        Validator::make($payload, $rule, $message)->validate();

        $payload['activity_type'] = ActivitySale::RULE_TYPE_ONE;
//        $payload['activity_name'] = $activity_name;
        $redis = app('redis.connection');
        $user = Auth::guard('admin')->user();
        $name = 'activity_' . $user->id;
        $aa = $redis->get($name);
        $array = json_decode($aa,true);
        $array[] = $payload;
        if($redis->set($name, json_encode($array))) {
            return $this->getResponseSuccess('保存成功', route('issue.index'));
        }
        throw new FormException( '保存失败');

    }
    /**
     * 添加页面
     *
     * @Author   stonefall
     * @DateTime 2019-06-5
     * @param    Request $request [description]
     * @return   [type]              [description]
     */
    public function create()
    {
        if (View::exists('Admin/issue/add')) {

            $redis = app('redis.connection');
            $user = Auth::guard('admin')->user();
            $name = 'activity_' . $user->id;
            $redis->set($name, json_encode([])) ;
            return view('Admin/issue/add');
        } else {
            return 'View Not Found';
        }
    }

    /**
     * 添加请求
     *
     * @Author   stonefall
     * @DateTime 2019-06-5
     * @param    Request $request [description]
     * @return   [type]              [description]
     */
    public function store(Request $request)
    {
        $payload = $request->all(['start_at', 'end_at']); 
        $rule = [
            'end_at' =>  'required|date|after_or_equal:start_at',
            'start_at' => 'required|date'
        ];
        $message = [
            'start_at.required' => '开始时间必填',
            'start_at.date' => '输入正确的开始时间',
            'end_at.required' => '结束时间必填',
            'end_at.date' => '输入正确的结束时间',
            'end_at.after_or_equal' => '结束时间应大于开始时间',
        ];
        Validator::make($payload, $rule, $message)->validate();
//        $time_end = ActivityType::Where([['start_at','<=',$payload['start_at']],['end_at','>=',$payload['start_at']]])
//            ->OrWhere([['start_at','<=',$payload['end_at']],['end_at','>=',$payload['end_at']]])
//            ->OrWhere([['start_at','>=',$payload['start_at']],['end_at','<=',$payload['end_at']]])->count();
//
//        if($time_end > 0){
//            throw new FormException(  '活动时间冲突，请重新选择');
//        }
        $redis = app('redis.connection');
        $user = Auth::guard('admin')->user();
        $name = 'activity_' . $user->id;
        $activity = $redis->get($name);
        $array = json_decode($activity,true);
        if(count($array) <= 0){
            throw new FormException(  '请为活动添加优惠礼包');
        }
        if(!$_FILES){
            throw new FormException(  '请添加图片');
        }
        $UploadService = new UploadService($request,'activity','photo','oss');
        $uploadresult = $UploadService->upload();
        if($uploadresult['status'] == UploadService::FailStatus){
            throw new FormException($uploadresult->message ?? '图片上传失败');
        }
        $payload['name'] = '注册发放';
        $payload['type'] = ActivityType::TYPE_TWO ;
        $payload['status'] = ActivityType::STATUS_FAIL;
        $payload['photo'] = $uploadresult['url'];
        try {
            $ActivityType = ActivityType::create($payload);
            foreach ($array as  $item=>$value){
                $array[$item]['activity_type'] = ActivitySale::TYPE_TWO;//发放时机，1后台，2注册
                $array[$item]['issue_type'] = 2;//发放时机，1后台，2注册
                $array[$item]['activity_type_id'] = $ActivityType->id;//活动礼包id
            }
            ActivitySale::insert($array);
            $redis->set($name,json_encode([]));
        } catch (\Exception $exception) {
            throw new FormException(\App::environment('local') ? $exception->getMessage() : '保存失败');
        }
        return $this->getResponseSuccess('保存成功,需手动启动', route('issue.index'));
    }

    /**
     * 修改状态请求
     *
     * @Author   stonefall
     * @DateTime 2019-05-31
     * @param    Request $request [description]
     * @return   [type]                [description]
     */
    public function upstatus(Request $request, $id)
    {
        try {
            $activity = ActivityType::findOrFail($id);
            if($activity->status == 1){
                $activity->status = 2;
            }else{
                $activity->status = 1;
               if( ActivityType::Where('status','1')->count()>0){
                   throw new Exception('不可同时有多个活动礼包开启');
               }
            }
            $activity->save();
        } catch (\Exception $exception) {
            throw new FormException(\App::environment('local') ? $exception->getMessage() : '保存失败');
        }

//        $list = new IssueService();
//        $list->marketing('60039');
        return $this->getResponse('操作成功');
    }


    /**
     * 编辑页面
     *
     * @Author   stonefall
     * @DateTime 2019-07-18
     * @param    Request $request [description]
     * @return   [type]                [description]
     */
    public function edit($id)
    {
        if (View::exists('Admin/coupon/edit')) {
            $data = ActivityType::find($id);
            $data['end_at'] = substr($data['end_at'],0,10);
            $data['start_at'] =substr($data['start_at'],0,10);
            return view('Admin/issue/edit', compact('data'));
        } else {
            return 'View Not Found';
        }
    }


}
